package com.cc.enterprise.controller;

/**
 * @author 新梦想.陈超
 * @version 2021.2
 * @Description: {TODO}
 * @date 2022/5/21 下午6:05
 */

import com.cc.enterprise.model.User;
import com.cc.enterprise.validate.ValidationGroup2;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "用户数据接口")
public class UserController {
    @ApiOperation(value = "查询用户", notes = "根据 id 查询用户")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户 id", required = true)
    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable Integer id) {
        return "/user/" + id;
    }

    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功！"),
            @ApiResponse(code = 500, message = "删除失败! ")})
    @ApiOperation(value = "删除用户", notes = "通过 id 删除用户")
    @DeleteMapping("/user/{id}")
    public Integer deleteUserById(@PathVariable Integer id) {
        return id;
    }

    @ApiOperation(value = "添加用户", notes = "添加一个用户，传入用户名和地址")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required =
                    true, defaultValue = "kate"),
            @ApiImplicitParam(paramType = "query", name = "address", value = "用户地址", required =
                    true, defaultValue = "changsha")})
    @PostMapping("/user")
    public String addUser(@RequestParam String username, @RequestParam String address) {
        return username + ":" + address;
    }
    /*惨叫校验*/
    @PostMapping("/user")
//    public List<String> addUser(@Validated User user, BindingResult result) {
    public List<String> addUser(@Validated(ValidationGroup2.class) User user, BindingResult result) {//分组校验
        List<String> errors = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError error : allErrors) {
                errors.add(error.getDefaultMessage());
            }
            return errors;
        }
        return null;
    }

    @ApiOperation(value = "修改用户", notes = "修改用户,传入用户信息")
    @PutMapping("/user")
    public String updateUser(@RequestBody User user) {
        return user.toString();
    }

    @GetMapping("/ignore")
    @ApiIgnore
    public void ingoreMethod() {
    }
}